# -*- coding: utf-8 -*-
import os
import os.path
import shutil
import time
import sys
import json
import zipfile

igorelist=["templates", "bower_components", "node_modules", "lib_repository"]

# 拷贝文件
def copyFiles(sourceDir, targetDir):
    for file in os.listdir(sourceDir):
        sourceFile = os.path.join(sourceDir, file)
        targetFile = os.path.join(targetDir, file)
        if os.path.isfile(sourceFile):
            if not os.path.exists(targetDir):
                os.makedirs(targetDir)

            if not os.path.exists(targetFile) or (os.path.exists(targetFile)):
                open(targetFile, "wb").write(open(sourceFile, "rb").read())

        if os.path.isdir(sourceFile):
            First_Directory = False
            copyFiles(sourceFile, targetFile)


# 文件夹是否为空
def isEmptyDir(targetDir):
    empty = False
    for root, dirs, files in os.walk(targetDir.encode('UTF8')):
        if (len(files) == 0):
            empty = True
    return empty


#删除一级目录下的所有文件：
def removeFileInFirstDir(targetDir):
    for file in os.listdir(targetDir):
        targetFile = os.path.join(targetDir, file)
        if os.path.isfile(targetFile):
            os.remove(targetFile)


#删除一级目录下的所有文件但不删除自身：
def cleanDir(Dir):
    if os.path.isdir(Dir):
        paths = os.listdir(Dir)
        for path in paths:
            filePath = os.path.join(Dir, path)
            if os.path.isfile(filePath):
                try:
                    os.remove(filePath)
                except os.error:
                    print "error"
            elif os.path.isdir(filePath):
                if filePath[-4:].lower() == ".svn".lower():
                    continue
                shutil.rmtree(filePath, True)
    return True


#删除一级目录下的所有文件含自身：
def delDir(Dir):
    shutil.rmtree(Dir, True)
    return True

#zip
def zip_dir(dirname,zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else :
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))

    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        #print arcname
        zf.write(tar,arcname)
    zf.close()

#文件覆盖
def coverFiles(sourceDir, targetDir):
    for file in os.listdir(sourceDir):
        sourceFile = os.path.join(sourceDir, file)
        targetFile = os.path.join(targetDir, file)
        #cover the files
        if os.path.isfile(sourceFile):
            open(targetFile, "wb").write(open(sourceFile, "rb").read())


#复制指定文件到目录：
def moveFileto(sourceDir, targetDir):
    shutil.copy(sourceDir, targetDir)


#返回当前日期
def getCurTime():
    nowTime = time.localtime()
    year = str(nowTime.tm_year)
    month = str(nowTime.tm_mon)
    if len(month) < 2:
        month = '0' + month
    day = str(nowTime.tm_yday)
    if len(day) < 2:
        day = '0' + day
    return (year + '-' + month + '-' + day)


def create_project(worksname):
    document_root = os.getcwd();
    if (worksname != "" and not os.path.exists(document_root + "/" + worksname)):
        os.makedirs(r'%s/%s' % (os.getcwd(), worksname))
    elif os.path.exists(document_root + "/" + worksname) and isEmptyDir(worksname):
        delDir(worksname)
        os.makedirs(r'%s/%s' % (os.getcwd(), worksname))
    else:
        print "the workspace exist ..."
        exit(0)


def writeVersionInfo(targetDir, info):
    open(targetDir, "wb").write(info)


if __name__ == "__main__":
    dir_list = []
    tag = ""

    try:
        tag = sys.argv[1]
    except IndexError:
        tag = "n"

    print "--------------Project List ( d|r|c|s|z )------------------"

    for fname in os.listdir(os.getcwd()):
        if os.path.isdir(fname) and not fname.startswith("."):
            if not fname in igorelist:
                dir_list.append(fname)

    for index, listName in enumerate(dir_list):
        print "[" + str(index) + "] " + listName

    if tag == "d":
        delNum = int(raw_input("Choose the del num:"))
        if delNum <= len(dir_list):
            if delDir(dir_list[delNum]):
                print "del success"
        else:
            print "out of range"
            exit(0)

    elif tag == "r":
        cleanNum = int(raw_input("Choose the clear num:"))
        if cleanNum <= len(dir_list):
            if cleanDir(dir_list[cleanNum]):
                print "clean success"
        else:
            print "out of range"
            exit(0)

    elif tag=="s":
        project_num=input("Project Num:")
        project=dir_list[project_num]
        #port=raw_input("Port:")
        #port if port else 8088
        #os.system("python httpServer.py "+port+" "+project+" -l")
        os.system("sh gulp.sh server")

    elif tag=="z":
        project=""
        if len(dir_list)==0:
            project="templates"
            choose_tpl=raw_input("Are you sure zip templates?(y/n)")
            if choose_tpl=="y":
                zip_dir(project,project+".zip")
                print "create "+project+" successful"
            else:
                pass
        else:
            project_num=input("Project Num:")
            project=dir_list[project_num]
            zip_dir("./",project+".zip")
            print "create "+project+" successful"
        

    elif tag == "c":
        worksname = raw_input("Please type your project name:");
        workdesc=raw_input("Project desc:");

        #构建项目
        create_project(worksname)

        if os.path.exists("templates"):
            work_path = os.getcwd() + "/" + "templates"

            f=file(work_path+'/package.json')
            packageData = json.load(f)
            packageData["name"]=worksname
            packageData["project"]=worksname
            packageData["description"]=workdesc
            infoDta = json.dumps(packageData,sort_keys=True,indent=4)

            #构建依赖库
            copyFiles(work_path, worksname)
            writeVersionInfo(worksname + "/html/build/rjs.sh", "#!/bin/sh"+"\n"+"Cur_Dir=$(pwd)"+"\n"+"cd ./"+
                             worksname+"/html/build"+"\n"+"node r.js -o build.js"+"\n"+"cd ../../"+"\n"+"sh gulp.sh rmin")
            writeVersionInfo(worksname + "/README.md", worksname + "\n" + getCurTime())
            writeVersionInfo(worksname+"/package.json",infoDta)
            if os.path.exists(worksname+"/.git"):
                delDir(worksname+"/.git")

            if os.path.exists(worksname+"/tasks"):
                delDir(worksname+"/tasks")

            openService=raw_input("Create the webservice:(y/n)");
            if openService=="y":
                 #port=raw_input("Port:")
                 #port if port else 8088
                 #os.system("python httpServer.py "+port+" "+worksname+" -l")
                 os.chdir("./"+worksname)
                 os.system("sh gulp.sh server")
            else:
                pass
            print "create project " + worksname + " successful!"

        else:
            print "check your templates"

    else:
        pass
